import { Creature, Feature, Glyph } from '$lib/components';
import { Ground } from '$lib/content/ground';
import { Door } from '$lib/door';
import { hasComponent } from '$lib/ecs';
import { Item } from '$lib/item';
import { decode } from '$lib/util';
import { Wall } from './wall';

const X = '▬│─┌││└├─┐─┬┘┤┴┼';

export const renderWall = (ns) => {
  return X[ns.left * 8 + ns.top * 4 + ns.right * 2 + ns.bottom * 1];
};

export const postProcess = (tiles) => {
  const width = tiles[0].length;
  const height = tiles.length;
  const line0 = Array.from({length: width});
  const line1 = Array.from({length: width}, () => { return {
    left: false,
    right: false,
    top: false,
    bottom: false,
    isWall: false,
    renderWall: false,
  }});
  for (let y = 0; y <= height; ++y) {
    for (let x = 0; x < width; ++x) {
      line0[x] = {...line1[x]};
      line1[x] = {
        left: false,
        right: false,
        top: false,
        bottom: false,
        isWall: false,
        renderWall: false,
      };
    }
    for (let x = 0; x < width; ++x) {
      if (y < height && tiles[y][x].isWall) {
        line1[x].isWall = tiles[y][x].isWall;
        line1[x].renderWall = tiles[y][x].renderWall;
        if (line0[x].isWall) {
          line0[x].bottom = true;
          line1[x].top = true;
        }
        if (x > 0 && line1[x-1].isWall) {
          line1[x-1].right = true;
          line1[x].left = true;
        }
      }
    }
    if (y > 0) {
      for (let x = 0; x < width; ++x) {
        if (line0[x].renderWall) {
          tiles[y-1][x].glyph = renderWall(line0[x]);
        }
      }
    }
  }
  return tiles.slice(1, height-1).map((line) => line.slice(1, width-1));
};

export const renderStack = (world, stack) => {
  let entity;
  let etype: string;
  let background = '#ccc';
  const extra = {};
  for (let e of stack) {
    if (hasComponent(world, Creature, e)) {
      entity = e;
      etype = 'creature';
    } else if (hasComponent(world, Item, e) && etype !== 'creature') {
      entity = e;
      etype = 'item';
    } else if (hasComponent(world, Feature, e) && etype !== 'item' && etype !== 'creature') {
      entity = e;
      etype = 'feature';
    } else if (hasComponent(world, Ground, e) && entity === undefined) {
      entity = e;
      etype = 'ground';
    }
    if (hasComponent(world, Wall, e) || hasComponent(world, Door, e)) {
      extra.isWall = true;
      extra.renderWall = hasComponent(world, Wall, e);
    }
  }
  if (entity === undefined) {
    return {
      glyph: ' ',
    };
  }
  const glyph = decode(Glyph.glyph[entity]);
  const color = decode(Glyph.color[entity]);
  // background = decode(Glyph.background[entity] ?? '');
  return {
    glyph,
    visible: true,
    color,
    background,
    ...extra,
  };
};
